package util

import (
	"gitee.com/kisgod/Lamborighi/Server/config"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
)

type Log struct {
	info  *log.Logger
	error *log.Logger
	debug *log.Logger
	fatal *log.Logger
	sql   *log.Logger
}

func initLogWriter(l LogLevel) io.Writer {
	logPath, err := filepath.Abs(config.GetLogPath())
	if err != nil {
		log.Fatal("日志文件错误: ", err)
	}

	logFile := filepath.Join(logPath, l.String()+".info")
	fileHandle, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalln("打开日志文件失败: ", err)
	}

	if config.APP_MODE == "dev" || config.APP_MODE == "test" {
		if l == ErrorLog || l == FatalLog {
			return io.MultiWriter(os.Stderr, fileHandle)
		} else {
			return io.MultiWriter(os.Stdout, fileHandle)
		}
	}

	return io.Writer(fileHandle)
}

func (logger *Log) Info(message ...interface{}) {
	if logger.info == nil {
		logger.info = log.New(
			initLogWriter(InfoLog),
			"["+strings.ToUpper(InfoLog.String())+"] ",
			log.Ldate|log.Ltime|log.Lshortfile)
	}
	logger.info.Println(message)
}

func (logger *Log) Error(message ...interface{}) {
	if logger.error == nil {
		logger.error = log.New(
			initLogWriter(ErrorLog),
			"["+strings.ToUpper(ErrorLog.String())+"] ",
			log.Ldate|log.Ltime|log.Lshortfile)
	}
	logger.error.Println(message)
}

func (logger *Log) Debug(message ...interface{}) {
	if logger.debug == nil {
		logger.debug = log.New(
			initLogWriter(DebugLog),
			"["+strings.ToUpper(DebugLog.String())+"] ",
			log.Ldate|log.Ltime|log.Lshortfile)
	}
	logger.debug.Println(message)
}

func (logger *Log) Fatal(message ...interface{}) {
	if logger.fatal == nil {
		logger.fatal = log.New(
			initLogWriter(FatalLog),
			"["+strings.ToUpper(FatalLog.String())+"] ",
			log.Ldate|log.Ltime|log.Lshortfile)
	}
	logger.fatal.Fatalln(message)
}

func (logger *Log) GetSqlLogger() *log.Logger {
	if logger.sql == nil {
		logger.sql = log.New(
			initLogWriter(SqlLog),
			"["+strings.ToUpper(SqlLog.String())+"] ",
			log.Ldate|log.Ltime)
	}
	return logger.sql
}
